using UnityEngine;

public static class Geometry
{
    //-------------------- LineIntersection2D-------------------------
    //
    //	Given 2 lines in 2D space AB, CD this returns true if an 
    //	intersection occurs and sets dist to the distance the intersection
    //  occurs along AB. Also sets the 2d vector point to the point of
    //  intersection
    //-----------------------------------------------------------------
    public static bool LineIntersection2D(Vector2 a, Vector2 b, Vector2 c, Vector2 d, ref float dist, ref Vector2 point)
    {
        float rTop = (a.y - c.y) * (d.x - c.x) - (a.x - c.x) * (d.y - c.y);
        float rBot = (b.x - a.x) * (d.y - c.y) - (b.y - a.y) * (d.x - c.x);

        float sTop = (a.y - c.y) * (b.x - a.x) - (a.x - c.x) * (b.y - a.y);
        float sBot = (b.x - a.x) * (d.y - c.y) - (b.y - a.y) * (d.x - c.x);

        if ((rBot == 0) || (sBot == 0))
        {
            //lines are parallel
            return false;
        }

        float r = rTop / rBot;
        float s = sTop / sBot;

        if ((r > 0) && (r < 1) && (s > 0) && (s < 1))
        {
            dist = (a - b).magnitude * r;

            point = a + r * (b - a);

            return true;
        }
        else
        {
            dist = 0;

            return false;
        }
    }

    public static bool LineIntersectionXZ(Vector3 a, Vector3 b, Vector3 c, Vector3 d, ref float dist, ref Vector3 point)
    {
        Vector2 refPoint = Vector2.zero;
        ;
        bool intersection = LineIntersection2D(new Vector2(a.x, a.z), new Vector2(b.x, b.z), 
            new Vector2(c.x, c.z),
            new Vector2(d.x, d.z),
            ref dist, ref refPoint);

        point.x = refPoint.x;
        point.y = 0;
        point.z = refPoint.y;

        return intersection;
    }
}